package panels.util;

import java.awt.Graphics;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JPanel;

import panels.PaintPanel;
import controllers.ComponentObserver;

public class CopyPanel extends JPanel implements Observer, Runnable {

	private static final long serialVersionUID = 1L;
	private ComponentObserver	observed = null;
	private PaintPanel			renderer = null;
	private Thread				drawThread = null;
	private boolean				redraw = true;
	private long				refreshRate = 10;
	
	public CopyPanel() {
		observed = new ComponentObserver();
		observed.addObserver(this);
		drawThread = new Thread(this);
		drawThread.start();
		this.setDoubleBuffered(true);
	}
	
	@Override
	public void paint(Graphics G) {
		System.out.println("paint");
		if (renderer!=null) {
			renderer.setPaintComponent(this);
			renderer.paint(G);
			renderer.setPaintComponent(renderer);
		}
	}

    public PaintPanel getRenderer() {
		return renderer;
	}

	public void setRenderer(PaintPanel renderer) {
		this.renderer = renderer;
		if (observed!=null) {
			observed.setWatched(this.renderer);
		}
	}

	@Override
	public void update(Observable o, Object arg) {
		this.setRedraw(true);
	}

	@Override
	public void run() {
		boolean running = true;
		while(running) {
			this.paintImmediately(this.getVisibleRect());
			try {
				Thread.sleep(refreshRate);
			} catch (InterruptedException e) {
				running = false;
			}
		}
	}

	public boolean isRedraw() {
		return redraw;
	}

	public void setRedraw(boolean redraw) {
		this.redraw = redraw;
	}


}
